package com.meiyuetao.myt.md.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import lab.s2jh.core.util.DateUtils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.meiyuetao.myt.kuajing.entity.KjBillInfo;
import com.meiyuetao.myt.kuajing.entity.KjHeaderInfo.KjActionTypeEnum;
import com.meiyuetao.myt.kuajing.entity.KjOrderDetailInfo;
import com.meiyuetao.myt.kuajing.entity.KjOrderInfo;
import com.meiyuetao.myt.kuajing.entity.KjPaymentInfo;
import com.meiyuetao.myt.kuajing.entity.KjSkuInfo;

@Service
public class KuajingMessageService{
    private static String url = "http://113.204.136.28/KJClientReceiver/Data.aspx";
    public static String userName = "MYTC102015";
    public static String passWord = "MYTC102015";
    public static String eshopEntName = "重庆美月淘电子商务有限公司";
    public static int ACTION_TYPE_NEW = 1;
    public static int ACTION_TYPE_EDIT = 2;
    public static int ACTION_TYPE_PAUSE = 3;

    public Boolean postMessage(String xmlString){
        String postData = "";
        try {
            postData = new String(Base64.encodeBase64(xmlString.getBytes()), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String response = null;
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient client = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("data", postData));
        UrlEncodedFormEntity entity;
        // 设置Post数据
        try {
            entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(entity);
            HttpResponse httpResponse;
            //post请求  
            httpResponse = client.execute(httpPost);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == status) {
                System.out.println("OK");
            }
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                response = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println("response:" + response);
                return Boolean.valueOf(response);
            }
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
        return Boolean.FALSE;
    }

    public String generateBillInfoXml(KjBillInfo kjBillInfo){
        String uuid = UUID.randomUUID().toString();
        String md5Pwd = DigestUtils.md5DigestAsHex((uuid + passWord).getBytes());
        String xmlString = 
                "<?xml version='1.0' encoding='utf-8'?>"
                + "<DTC_Message>" 
                    + "<MessageHead>"
                        + "<MessageType>BILL_INFO</MessageType>" 
                        + "<MessageId>"+ uuid + "</MessageId>"
                        + "<ActionType>"+ 1 +"</ActionType>"
                        + "<MessageTime>"+ DateUtils.formatTime(new Date()) +"</MessageTime>"
                        + "<SenderId>"+ userName +"</SenderId>"
                        + "<ReceiverId>CQITC</ReceiverId>"
                        + "<UserNo>"+ userName + "</UserNo>"
                        + "<Password>"+ md5Pwd + "</Password>"
                    + "</MessageHead>"
                    + "<MessageBody>"
                        + "<DTCFlow>"
                            + "<BILL_INFO>"
                                + "<ORIGINAL_ORDER_NO>"+ kjBillInfo.getOriginalOrderNo() + "</ORIGINAL_ORDER_NO>"
                                + "<BIZ_TYPE_CODE>"+ kjBillInfo.getBizTypeCode() +"</BIZ_TYPE_CODE>"
                                + "<BIZ_TYPE_NAME>"+ kjBillInfo.getBizTypeName() +"</BIZ_TYPE_NAME>"
                                + "<TRANSPORT_BILL_NO>"+ kjBillInfo.getTransportBillNo() +"</TRANSPORT_BILL_NO>"// 分运单号
                                + "<ESHOP_ENT_CODE>"+ kjBillInfo.getEshopEntCode() +"</ESHOP_ENT_CODE>"// 电商企业代码
                                + "<ESHOP_ENT_NAME>"+ kjBillInfo.getEshopEntName() +"</ESHOP_ENT_NAME>"// 电商企业名称
                                + "<CUSTOMS_CODE>"+ kjBillInfo.getCustomCode() +"</CUSTOMS_CODE>"// 关区代码
                                + "<CUSTOMS_NAME>"+ kjBillInfo.getCustomsName() +"</CUSTOMS_NAME>"// 关区名称
                                + "<LOGISTICS_ENT_CODE>"+ kjBillInfo.getLogisticsEntCode() +"</LOGISTICS_ENT_CODE>"// 物流企业代码
                                + "<LOGISTICS_ENT_NAME>"+ kjBillInfo.getLogisticsEntName() +"</LOGISTICS_ENT_NAME>"// 物流企业名称
                                + "<QTY>"+ kjBillInfo.getQty() +"</QTY>"// 数量
                                + "<RECEIVER_ID_NO>"+ kjBillInfo.getReceiverIdNo() +"</RECEIVER_ID_NO>"// 收件人身份证号
                                + "<RECEIVER_NAME>"+ kjBillInfo.getReceiverName() +"</RECEIVER_NAME>"// 收件人姓名
                                + "<RECEIVER_ADDRESS>"+ kjBillInfo.getReceiverAddress() +"</RECEIVER_ADDRESS>"// 收件人地址
                                + "<RECEIVER_TEL>"+ kjBillInfo.getReceiverAddress() +"</RECEIVER_TEL>"// 收件人电话
                            + "</BILL_INFO>"
                        + "</DTCFlow>" 
                    + "</MessageBody>"
                + "</DTC_Message>";
        return xmlString;
    }

    public String generateOrderInfoXml(KjOrderInfo kjOrderInfo) {
        String uuid = UUID.randomUUID().toString();
        String md5Pwd = DigestUtils.md5DigestAsHex((uuid + passWord).getBytes());
        String xmlStringPrefix = 
                "<?xml version='1.0' encoding='utf-8'?>"
                + "<DTC_Message>"
                    + "<MessageHead>"
                        + " <MessageType>ORDER_INFO</MessageType>"
                        + "<MessageId>" + uuid + "</MessageId>"
                        + "<ActionType>1</ActionType>"
                        + "<MessageTime>" + DateUtils.formatTime(new Date()) + "</MessageTime>"
                        + " <SenderId>" + userName + "</SenderId>"
                        + " <ReceiverId>CQITC</ReceiverId>"
                        + " <UserNo>" + userName + "</UserNo>"
                        + " <Password>" + md5Pwd + "</Password>"
                    + "</MessageHead>"
                    + " <MessageBody>"
                        + " <DTCFlow>"
                            + "<ORDER_HEAD>"
                                + "<CUSTOMS_CODE>"+ kjOrderInfo.getCustomersCode() +"</CUSTOMS_CODE>" // 申报海关代码 
                                + "<BIZ_TYPE_CODE>"+ kjOrderInfo.getBizTypeCode() +"</BIZ_TYPE_CODE>" // 业务类型 
                                + "<ORIGINAL_ORDER_NO>"+ kjOrderInfo.getOriginalOrderNo() +"</ORIGINAL_ORDER_NO>" // 原始订单编号
                                + "<ESHOP_ENT_CODE>"+ kjOrderInfo.getEshopEntCode() +"</ESHOP_ENT_CODE>" // 电商企业代码
                                + "<ESHOP_ENT_NAME>"+ kjOrderInfo.getEshopEntName() + "</ESHOP_ENT_NAME>" // 电商企业名称
                                + "<DESP_ARRI_COUNTRY_CODE>"+ kjOrderInfo.getDespArriCountryCode() +"</DESP_ARRI_COUNTRY_CODE>" // 起运国 
                                + "<SHIP_TOOL_CODE>"+ kjOrderInfo.getShipToolCode() +"</SHIP_TOOL_CODE>" // 运输方式 TODO
                                + "<RECEIVER_ID_NO>"+ kjOrderInfo.getReceiverIdNo() +"</RECEIVER_ID_NO>" // 收货人身份证号码 
                                + "<RECEIVER_NAME>"+ kjOrderInfo.getReceiverName() +"</RECEIVER_NAME>" // 收货人姓名 
                                + "<RECEIVER_ADDRESS>"+ kjOrderInfo.getReceiverAddress() +"</RECEIVER_ADDRESS>" // 收货人地址
                                + "<RECEIVER_TEL>"+ kjOrderInfo.getReceiverTel() +"</RECEIVER_TEL>" // 收货人电话
                                + "<GOODS_FEE>"+ kjOrderInfo.getGoodsFee() +"</GOODS_FEE>" // 货款总额
                                + "<TAX_FEE>"+ kjOrderInfo.getTaxFee() +"</TAX_FEE>" // 税金总额 
                                + "<GROSS_WEIGHT>"+ kjOrderInfo.getGrossWeight() +"</GROSS_WEIGHT>" // 毛重
                                + "<SORTLINE_ID>"+ kjOrderInfo.getSortlingId() +"</SORTLINE_ID>"; // 代理企业代码  
        String xmlStringSuffix = "</ORDER_HEAD>"
                        + "</DTCFlow>" 
                    + "</MessageBody>" 
                + "</DTC_Message>";
        return xmlStringPrefix + getOrderDetailXml(kjOrderInfo.getKjOrderDetailInfos()) + xmlStringSuffix;
    }

    private String getOrderDetailXml(List<KjOrderDetailInfo> kjOrderDetailInfos) {
        StringBuilder orderDetailXml = new StringBuilder();
        for(KjOrderDetailInfo kodi: kjOrderDetailInfos){
            orderDetailXml.append("<ORDER_DETAIL>")
                          .append("<SKU>").append(kodi.getSku()).append("</SKU>") // 商品货号
                          .append("<GOODS_SPEC>").append(kodi.getGoodsSpec()).append("</GOODS_SPEC>") // 规格型号
                          .append("<CURRENCY_CODE>").append(kodi.getCurrencyCode()).append("</CURRENCY_CODE>") // 币制代码 TODO
                          .append("<PRICE>").append(kodi.getPrice()).append("</PRICE>") // 商品单价
                          .append("<QTY>").append(kodi.getQty()).append("</QTY>") // 商品数量
                          .append("<GOODS_FEE>").append(kodi.getGoodsFee()).append("</GOODS_FEE>") // 商品总价
                          .append("<TAX_FEE>").append(kodi.getTaxFee()).append("</TAX_FEE>") // 税款金额 TODO
                          .append("</ORDER_DETAIL>");
        }
        return orderDetailXml.toString();
    }

    public String generateSkuInfoXml(KjSkuInfo kjSkuInfo) {
        int actionType = ACTION_TYPE_NEW;
        if(kjSkuInfo.getActionType() == KjActionTypeEnum.EDIT){
            // 变更
            actionType = ACTION_TYPE_EDIT;
        }else if(kjSkuInfo.getActionType() == KjActionTypeEnum.PAUSE){
            // 暂停
            actionType = ACTION_TYPE_PAUSE;
        }
        String uuid = UUID.randomUUID().toString();
        String md5Pwd = DigestUtils.md5DigestAsHex((uuid + passWord).getBytes());
        String xmlString = 
                "<?xml version='1.0' encoding='utf-8'?>"
                + "<DTC_Message>" 
                    + "<MessageHead>"
                        + "<MessageType>SKU_INFO</MessageType>" 
                        + "<MessageId>"+ uuid + "</MessageId>"
                        + "<ActionType>"+ actionType +"</ActionType>"
                        + "<MessageTime>"+ DateUtils.formatTime(new Date()) +"</MessageTime>"
                        + "<SenderId>"+ userName +"</SenderId>"
                        + "<ReceiverId>CQITC</ReceiverId>"
                        + "<UserNo>"+ userName + "</UserNo>"
                        + "<Password>"+ md5Pwd + "</Password>"
                    + "</MessageHead>"
                    + "<MessageBody>"
                        + "<DTCFlow>"
                            + "<SKU_INFO>"
                                + "<ESHOP_ENT_CODE>"+ userName + "</ESHOP_ENT_CODE>"
                                + "<ESHOP_ENT_NAME>"+ eshopEntName +"</ESHOP_ENT_NAME>"
                                + "<SKU>"+ kjSkuInfo.getSku() +"</SKU>"// 商品货号
                                + "<GOODS_NAME>"+ kjSkuInfo.getGoodsName() +"</GOODS_NAME>"// 商品名称
                                + "<GOODS_SPEC>"+ kjSkuInfo.getGoodesSpec() +"</GOODS_SPEC>"// 规格型号
                                + "<DECLARE_UNIT>"+ kjSkuInfo.getDeclareUnit() +"</DECLARE_UNIT>"// 申报计量单位
                                + "<POST_TAX_NO>"+ kjSkuInfo.getPostTaxNO() +"</POST_TAX_NO>"// 行邮税号
                                + "<LEGAL_UNIT>"+ kjSkuInfo.getLegalUnit() +"</LEGAL_UNIT>"// 法定计量单位
                                + "<CONV_LEGAL_UNIT_NUM>"+ kjSkuInfo.getConvLegalUnitNum() +"</CONV_LEGAL_UNIT_NUM>"// 法定计量单位折算数量
                                + "<HS_CODE>"+ kjSkuInfo.getHsCode() +"</HS_CODE>"// 商品HS编码
                                + "<IN_AREA_UNIT>"+ kjSkuInfo.getInAreaUnit() +"</IN_AREA_UNIT>"// 入区计量单位
                                + "<CONV_IN_AREA_UNIT_NUM>"+kjSkuInfo.getConvInAreaUnitNum()+"</CONV_IN_AREA_UNIT_NUM>"// 入区计量单位折算数量
                                + "<IS_EXPERIMENT_GOODS>"+ (kjSkuInfo.getIsExperimentGoods()==Boolean.TRUE?1:0) +"</IS_EXPERIMENT_GOODS>"// 是否试点商品
                                + getSkuInfoOptional(kjSkuInfo)
                            + "</SKU_INFO>"
                        + "</DTCFlow>" 
                    + "</MessageBody>"
                + "</DTC_Message>";
        return xmlString;
    }

    public String getSkuInfoOptional(KjSkuInfo info) {
        String optional = "";
        // 国家地区代码
        if(StringUtils.isNotBlank(info.getOriginCountryCode())){
            optional += "<ORIGIN_COUNTRY_CODE>"+info.getOriginCountryCode()+"</ORIGIN_COUNTRY_CODE>";
        }
        // 国外生产企业是否在中国注册备案（食药监局、国家认监委）
        if(info.getIsCncaPor()!=null&&info.getIsCncaPor()){
            optional += "<IS_CNCA_POR>"+(info.getIsCncaPor()==Boolean.TRUE?1:0)+"</IS_CNCA_POR>";
        }
        // 食药监局、国家认监委备案附件
        if(StringUtils.isNotBlank(info.getCncaPorDoc())){
            optional += "<CNCA_POR_DOC>"+info.getOriginCountryCode()+"</CNCA_POR_DOC>";
        }
        // ORIGIN_PLACE_CERT    原产地证书
        if(StringUtils.isNotBlank(info.getOriginPlaceCert())){
            optional += "<ORIGIN_PLACE_CERT>"+info.getOriginCountryCode()+"</ORIGIN_PLACE_CERT>";
        }
        // TEST_REPORT    境外官方及第三方机构的检测报告
        if(StringUtils.isNotBlank(info.getTestReport())){
            optional += "<TEST_REPORT>"+info.getOriginCountryCode()+"</TEST_REPORT>";
        }
        // LEGAL_TICKET    合法采购证明（国外进货发票或小票）
        if(StringUtils.isNotBlank(info.getLegalTicket())){
            optional += "<LEGAL_TICKET>"+info.getOriginCountryCode()+"</LEGAL_TICKET>";
        }
        // MARK_EXCHANGE    外文标签的中文翻译件
        if(StringUtils.isNotBlank(info.getMarkExchange())){
            optional += "<MARK_EXCHANGE>"+info.getOriginCountryCode()+"</MARK_EXCHANGE>";
        }
        // CHECK_ORG_CODE    施检机构的代码
        if(StringUtils.isNotBlank(info.getCheckOrgCode())){
            optional += "<CHECK_ORG_CODE>"+info.getOriginCountryCode()+"</CHECK_ORG_CODE>";
        }
        // SUPPLIER_NAME    供应商名称
        if(StringUtils.isNotBlank(info.getSupplierName())){
            optional += "<SUPPLIER_NAME>"+info.getOriginCountryCode()+"</SUPPLIER_NAME>";
        }
        return optional;
    }

    public String generatePaymentInfoXml(KjPaymentInfo info) {
        String uuid = UUID.randomUUID().toString();
        String md5Pwd = DigestUtils.md5DigestAsHex((uuid + passWord).getBytes());
        String xmlString = 
                "<?xml version='1.0' encoding='utf-8'?>"
                + "<DTC_Message>" 
                    + "<MessageHead>"
                        + "<MessageType>PAYMENT_INFO</MessageType>" 
                        + "<MessageId>"+ uuid +"</MessageId>"
                        + "<ActionType>1</ActionType>"
                        + "<MessageTime>"+ DateUtils.formatTime(new Date()) +"</MessageTime>"
                        + "<SenderId>"+ userName +"</SenderId>"
                        + "<ReceiverId>CQITC</ReceiverId>"
                        + "<UserNo>"+ userName +"</UserNo>"
                        + "<Password>"+ md5Pwd +"</Password>"
                    + "</MessageHead>"
                    + " <MessageBody>"
                        + " <DTCFlow>"
                            + "<PAYMENT_INFO>"
                                + "<CUSTOMS_CODE>"+ info.getCustomsCode() +"</CUSTOMS_CODE>"
                                + "<BIZ_TYPE_CODE>"+ info.getBizTypeCode() +"</BIZ_TYPE_CODE>"
                                + "<ESHOP_ENT_CODE>"+ userName +"</ESHOP_ENT_CODE>"
                                + "<ESHOP_ENT_NAME>"+ info.getEshopEntName() +"</ESHOP_ENT_NAME>"
                                + "<PAYMENT_ENT_CODE>"+ info.getPaymentEntCode() +"</PAYMENT_ENT_CODE>"
                                + "<PAYMENT_ENT_NAME>"+ info.getPaymentEntName() +"</PAYMENT_ENT_NAME>"
                                + "<PAYMENT_NO>"+ info.getPaymentNo() +"</PAYMENT_NO>"
                                + "<ORIGINAL_ORDER_NO>"+ info.getOriginalOrderNo() +"</ORIGINAL_ORDER_NO>"
                                + "<PAY_AMOUNT>"+ info.getPayAmount() +"</PAY_AMOUNT>"
                                + "<GOODS_FEE>"+ info.getGoodsFee() +"</GOODS_FEE>"
                                + "<TAX_FEE>"+ info.getTaxFee() +"</TAX_FEE>"
                                + "<CURRENCY_CODE>"+ info.getCurrencyCode() +"</CURRENCY_CODE>"
                                + "<MEMO>"+ info.getMemo() +"</MEMO>"
                            + "</PAYMENT_INFO>"
                        + "</DTCFlow>"
                    + "</MessageBody>" 
                + "</DTC_Message>";
        return xmlString;
    }
}
